package com.zzvcom.webapp.action;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.zzvcom.persist.model.admin.Image;
import com.zzvcom.service.admin.ImageManager;
import com.zzvcom.utils.ConfigUtil;
import com.zzvcom.utils.DateUtil;
import com.zzvcom.utils.ImageResizer;
@Controller
@Scope("prototype")
public class UploadAction
{

    private File Filedata;

    private String FiledataFileName;

    private String FiledataContentType;

    private static final String basePath = "userfiles";   
    
    private ImageManager im;
    
    private String msg;

    // 上传文件呵呵
    private String pathSplit(String timeStr, String o, String n)
    {
        StringBuffer sb = new StringBuffer();
        for (String a : timeStr.split(o))
        {
            sb.append(a);
            sb.append(n);
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }

    public static String format(Date date, String parttern)
    {
        DateFormat df = new SimpleDateFormat(parttern);
        return df.format(date);
    }

    public String execute()
    {

        if (Filedata != null && Filedata.length() > 0)
        {
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String datastr = format(new Date(), "yyyy@MM@dd");
            String appPath=ServletActionContext.getServletContext().getRealPath("");
            //System.out.println("appPath:"+appPath);            
            String uploadPath = ServletActionContext.getServletContext()
                    .getRealPath(
                            basePath + File.separator
                                    + pathSplit(datastr, "@", File.separator));
            String ext = FiledataFileName.substring(FiledataFileName.lastIndexOf(".")).toLowerCase();
            File path = new File(uploadPath);
            if (!path.exists())
            {
                path.mkdirs();
            }          
            String newName = uuid + ext;
            String newPath = uploadPath + File.separator + newName;
            Filedata.renameTo(new File(newPath));
            Integer middleWidth=Integer.valueOf(ConfigUtil.getValue("middle_image_width"));
            Integer smallWidth=Integer.valueOf(ConfigUtil.getValue("small_image_width"));
            String middlePath=uploadPath + File.separator +uuid+"@middle"+ext;
            String smallPath=uploadPath + File.separator +uuid+"@small"+ext;
            ImageResizer resizer=new ImageResizer();
            resizer.resizeImageWidth(new File(newPath), middlePath, middleWidth, ext.substring(1));
            resizer.resizeImageWidth(new File(newPath), smallPath, smallWidth, ext.substring(1));
            String relativePath=uploadPath.substring(appPath.length());           
            relativePath=relativePath.replaceAll("\\"+File.separator, "#")+"#"+newName;
            Image image=new Image();
            image.setAddtime(DateUtil.dateToNum14(new Date()));
            image.setPath(relativePath);
            image.setAlt(FiledataFileName.substring(0,FiledataFileName.lastIndexOf(".")));
            im.save(image); 
            msg="{'ok':true,'id':'"+image.getId()+"'}";
            return "msg";
            
        }
        msg="{'ok':false}";
        return "msg";
    }
    
    public String sload()//single Image no reizeed
    {
        if (Filedata != null && Filedata.length() > 0)
        {
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String datastr = format(new Date(), "yyyy@MM@dd");
            String appPath=ServletActionContext.getServletContext().getRealPath("");
            //System.out.println("appPath:"+appPath);            
            String uploadPath = ServletActionContext.getServletContext()
                    .getRealPath(
                            basePath + File.separator
                                    + pathSplit(datastr, "@", File.separator));
            String ext = FiledataFileName.substring(FiledataFileName.lastIndexOf(".")).toLowerCase();
            File path = new File(uploadPath);
            if (!path.exists())
            {
                path.mkdirs();
            }          
            String newName = uuid + ext;
            String newPath = uploadPath + File.separator + newName;
            Filedata.renameTo(new File(newPath)); 
            String relativePath=uploadPath.substring(appPath.length());           
            relativePath=relativePath.replaceAll("\\"+File.separator, "#")+"#"+newName;
            Image image=new Image();
            image.setAddtime(DateUtil.dateToNum14(new Date()));
            image.setPath(relativePath);
            image.setAlt(FiledataFileName.substring(0,FiledataFileName.lastIndexOf(".")));
            im.save(image); 
            msg="{'ok':true,'id':'"+image.getId()+"'}";
            return "msg";            
        }
        msg="{'ok':false}";
        return "msg";
    	
    }
    public String gload()
    {

        if (Filedata != null && Filedata.length() > 0)
        {
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String datastr = format(new Date(), "yyyy@MM@dd");
            String appPath=ServletActionContext.getServletContext().getRealPath("");
            //System.out.println("appPath:"+appPath);            
            String uploadPath = ServletActionContext.getServletContext()
                    .getRealPath(
                            basePath + File.separator
                                    + pathSplit(datastr, "@", File.separator));
            String ext = FiledataFileName.substring(FiledataFileName.lastIndexOf(".")).toLowerCase();
            File path = new File(uploadPath);
            if (!path.exists())
            {
                path.mkdirs();
            }          
            String newName = uuid + ext;
            String newPath = uploadPath + File.separator + newName;
            Filedata.renameTo(new File(newPath));           
            Integer smallWidth=105;   
            Integer smallHeight=70;   
            String smallPath=uploadPath + File.separator +uuid+"@small"+ext;
            ImageResizer resizer=new ImageResizer();           
            resizer.resizeImage(new File(newPath), smallPath, smallWidth,smallHeight, ext.substring(1));
            String relativePath=uploadPath.substring(appPath.length());           
            relativePath=relativePath.replaceAll("\\"+File.separator, "#")+"#"+newName;
            Image image=new Image();
            image.setAddtime(DateUtil.dateToNum14(new Date()));
            image.setPath(relativePath);
            image.setAlt(FiledataFileName.substring(0,FiledataFileName.lastIndexOf(".")));
            im.save(image); 
            msg="{'ok':true,'id':'"+image.getId()+"'}";
            return "msg";
            
        }
        msg="{'ok':false}";
        return "msg";
    }

    public File getFiledata()
    {
        return Filedata;
    }

    public void setFiledata(File filedata)
    {
        Filedata = filedata;
    }

    public String getFiledataFileName()
    {
        return FiledataFileName;
    }

    public void setFiledataFileName(String filedataFileName)
    {
        FiledataFileName = filedataFileName;
    }

    public String getFiledataContentType()
    {
        return FiledataContentType;
    }

    public void setFiledataContentType(String filedataContentType)
    {
        FiledataContentType = filedataContentType;
    }
    
    
    
    public ImageManager getIm()
	{
		return im;
	}
    @Autowired
	public void setIm(ImageManager im)
	{
		this.im = im;
	}

	public String getMsg()
	{
		return msg;
	}

	public void setMsg(String msg)
	{
		this.msg = msg;
	}
}
